package io.gitee.minelx.filesystem.init;

import io.gitee.minelx.filesystem.Path;

public enum OpenPolicy {
	EXISTS {
		@Override
		public void open(Path path, PathType pathType) {
			throwIfNotExists(path, pathType);
			throwIfTypeMismatch(path, pathType);
		}
	}, CREATE {
		@Override
		public void open(Path path, PathType pathType) {
			doCreate(path, pathType);
		}
	}, CREATE_IF_NOT_EXISTED {
		@Override
		public void open(Path path, PathType pathType) {
			if (path.exists()) {
				throwIfTypeMismatch(path, pathType);
				return;
			}
			// not exists
			doCreate(path, pathType);
		}
	}, __ {
		@Override
		public void open(Path path, PathType pathType) {
			// do nothing
		}
	};

	public abstract void open(Path path, PathType pathType);

	private static void doCreate(Path path, PathType pathType) {
		pathType.create(path);
	}

	private static void throwIfTypeMismatch(Path path, PathType pathType) {
		if (!pathType.isMatch(path)) {
			throw new IllegalArgumentException(String.format("'%s' is not a %s",
					path.absolutePath(),
					pathType.friendlyName()));
		}
	}

	private static void throwIfNotExists(Path path, PathType pathType) {
		if (!path.exists()) {
			throw new IllegalArgumentException("unable to open " + pathType.friendlyName() + " at: '" + path.absolutePath() + "' cause it's not existed.");
		}
	}
}
